<template>
  <div style="background-color: rgba(239, 250, 251, 1); padding: 20px; border-radius: 8px;">
    <a-card style=" padding: 10px;  border-radius: 4px;">
        <!-- 查询表单 -->
        <div style="padding: 20px;">
            <a-form :form="searchForm" layout="inline">
                <!-- 查询表单项 -->
                <a-form-item label="名称">
                    <a-input v-model="searchParams.name" />
                </a-form-item>
              <a-form-item label="类型">
                <a-select v-model="searchParams.type" @change="$forceUpdate()" style="width: 200px;" allowClear>
                  <a-select-option value="4">活动成果</a-select-option>
                  <a-select-option value="5">媒体成果</a-select-option>
                  <a-select-option value="6">学术论文</a-select-option>
                  <a-select-option value="10">项目成果</a-select-option>
                  <a-select-option value="12">科技成果</a-select-option>
                  <a-select-option value="13">期刊成果</a-select-option>
                  <a-select-option value="14">行业标准</a-select-option>
                  <a-select-option value="15">国家标准</a-select-option>
                  <a-select-option value="18">专题活动</a-select-option>
                  <a-select-option value="20">国际会议</a-select-option>
                  <a-select-option value="21">国际论坛</a-select-option>
                  <a-select-option value="9">其他</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="作者姓名">
                <a-input v-model="searchParams.authorName" />
              </a-form-item>
                <a-form-item>
                    <a-button type="primary" @click="searchFruit">查询</a-button>
                </a-form-item>
            </a-form>
        </div>
        <div style="text-align: right; margin: 10px;">
            <a-button type="primary" @click="showModal('add')" v-gw-permission="'nd_fruit_add'">新增</a-button>
        </div>

        <!-- 列表展示 -->
        <a-table :columns="columns" :dataSource="dataSource" :loading="loading" :rowKey="record => record.id" :pagination="false">
            <template slot="action" slot-scope="text, record">
                <a-button @click="edit(record)" v-gw-permission="'nd_fruit_edit'">编辑</a-button>
                &nbsp;&nbsp;
                <a-popconfirm
                    title="是否确认删除此条数据?"
                    ok-text="是"
                    cancel-text="否"
                    @confirm="remove(record)"
                >
                    <a-button type="danger" v-gw-permission="'nd_fruit_check'">删除</a-button>
                </a-popconfirm>
            </template>
        </a-table>
        <br/>
        <!-- 分页器 -->
        <a-pagination :show-total="total => `共${total}条`" :total="total" :current="pagination.current" :pageSize="pagination.pageSize" @change="handlePaginationChange" />

        <!-- 新增/编辑对话框 -->
        <a-modal :width="800" v-model:visible="modal.visible" :title="modal.title" @ok="handleOk" @cancel="handleCancel">
            <!-- 表单项 -->
            <a-form :form="modalForm" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }" >
                <!-- 表单项 -->
                <a-form-item label="名称" :required="true" :rules="[ { required: true, message: '请输入名称' } ]">
                    <a-input v-model="modal.formData.name" />
                </a-form-item>
                <a-form-item label="类型">
                    <a-select v-model="modal.formData.type" @change="$forceUpdate()">
                      <a-select-option value="4">活动成果</a-select-option>
                      <a-select-option value="5">媒体成果</a-select-option>
                      <a-select-option value="6">学术论文</a-select-option>
                      <a-select-option value="10">项目成果</a-select-option>
                      <a-select-option value="12">科技成果</a-select-option>
                      <a-select-option value="13">期刊成果</a-select-option>
                      <a-select-option value="14">行业标准</a-select-option>
                      <a-select-option value="15">国家标准</a-select-option>
                      <a-select-option value="18">专题活动</a-select-option>
                      <a-select-option value="20">国际会议</a-select-option>
                      <a-select-option value="21">国际论坛</a-select-option>
                      <a-select-option value="9">其他</a-select-option>
                    </a-select>
                </a-form-item>
                <div style="border: dashed 1px #D5D5D5; padding-top: 10px; margin-bottom: 10px;" :key="aindex" v-for="(auItem,aindex) in modal.formData.esTalentFruitAuthorList">
                    <a-form-item :label="'第'+(aindex+1)+'作者'">
                        <a-row :gutter="24">
                            <a-col span="16">
                                <a-input v-model="auItem.author" readonly/>
                                <div style="font-size: 12px; color: red;" v-if="aindex==0">
                                    请一行填写一个专家， 若有多个，请点击后方的”添加专家“按钮！
                                </div>
                            </a-col>
                            <a-col span="4">
                                <a-button @click="selectAuthor(aindex)">选择专家</a-button>
                            </a-col>
                            <a-col span="4">
                                <a-button type="primary" @click="addAuthor()" v-if="aindex == 0">添加专家</a-button>
                                <a-button type="danger" @click="deleteAuthor(aindex)" v-if="aindex != 0">删除专家</a-button>
                            </a-col>
                        </a-row>
                    </a-form-item>
                    <a-form-item :label="'第'+(oindex+1)+'单位'" :key="orgItem.id" v-for="(orgItem,oindex) in auItem.esTalentFruitAuthorOrgList">
                        <a-row :gutter="24">
                            <a-col span="16">
                                <a-input  v-model="orgItem.name"/>
                                <div style="font-size: 12px; color: red;" v-if="aindex==0 && oindex==0">请一行填写一个单位， 若有多个，请点击后方的”添加单位“按钮！</div>
                            </a-col>
                            <a-col span="7">
                                <a-button type="primary" @click="addOrgName(aindex)" v-if="oindex==0" ghost>添加单位</a-button>
                                <a-button type="danger" @click="deleteOrgName(aindex, oindex)"  v-if="oindex!=0">删除单位</a-button>
                            </a-col>
                        </a-row>
                    </a-form-item>
                </div>
                <a-form-item label="出版地">
                    <a-input v-model="modal.formData.pubPlace" />
                </a-form-item>
                <a-form-item label="发布时间">
                    <a-date-picker @change="onChange" v-model="modal.formData.pubTime" />
                </a-form-item>
                <a-form-item label="摘要">
                    <a-textarea v-model="modal.formData.summary" />
                </a-form-item>
            </a-form>
        </a-modal>


        <a-modal :width="400" v-model="selectAuthorModal" title="专家信息" :mask-closable="false">
            <div class="addCon">
                <a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }" >
                    <a-form-item label="姓名">
                        <a-select
                            show-search
                            @change ="changeSelect"
                            v-model="selectAuthorOrgUserId"
                            placeholder="请输入后在结果集中选择"
                            :show-arrow="false"
                            @search="getResultList"
                            :filter-option="false"
                            :not-found-content="expertListLoading ? undefined : null"
                        >
                            <a-spin v-if="expertListLoading" slot="notFoundContent" size="small" />
                            <a-select-option v-for="item in resultExpertList" :key="item.id">
                              {{ item.talentRealName}}{{item.talentCompany != null ? ('「' + item.talentCompany + '」') : ''}}
                            </a-select-option>
                        </a-select>
                    </a-form-item>
                </a-form>
            </div>
            <div slot="footer" class="div_margin_5" align="center">
                <a-button type="primary" :loading="selectAuthorLoading" @click="confirmSetAuthor()">确认</a-button>
                <a-button @click="cancelSelectAuthor()">取消</a-button>
            </div>
        </a-modal>
    </a-card>
  </div>
</template>

<script>
import {httpAction} from "@/api/esManage";
import {getFruitTypeName} from '@/utils/tools'

export default {
    props: {
        talentId: {
            type: String
        }
    },
    created() {
        this.fetchData();
    },
    data() {
        return {
            searchForm: null,
            searchParams: {
                talentId: this.talentId
            },
            dataSource: [],
            columns: [
                {
                    title: "序号",
                    dataIndex: "key",
                    align: "center",
                    width: 80,
                    customRender: (text,record,index) => `${index+1}`,//此处为重点
                },
                {
                    title: '名称',
                    dataIndex: 'name',
                    width: 400,
                    ellipsis: true
                },
                {
                    title: '类型',
                    customRender: (text,record) => {
                      return getFruitTypeName(record.type);
                    },
                },
                {
                    title: '作者',
                    dataIndex: 'authorNames',
                },
                {
                    title: '时间',
                    dataIndex: 'pubTime',
                    customRender: (text,record) => `${record.pubTime == null || record.pubTime == '' ? '' : record.pubTime.substring(0, 10)}`,//此处为重点
                },
                {
                  title: '状态',
                  customRender: (text,record) => `${record.status == 0 ? '待审核' :
                    record.status == 1 ? '待发布' :
                      record.status == 2 ? '待归档' :
                        record.status == 3 ? '已归档' :
                          record.status == 4 ? '已驳回' : '已入库' }`,
                },
                {
                    title: '操作',
                    dataIndex: 'action',
                    width: 200,
                    scopedSlots: { customRender: 'action' }
                }
            ],
            loading: false,
            total: 0,
            pagination: {
                current: 1,
                pageSize: 10
            },
            modalForm: null,
            modal: {
                visible: false,
                title: '',
                record: null,
                formData: {
                    dcode: '',
                    esTalentFruitAuthorList:[]
                }
            },
            showFruitModal: false,
            expertId: null,

            allExpertList: [],
            resultExpertList: [],
            selectAuthorOrgUserId: '',
            selectAuthorObj: {},
            selectAuthorModal: false,
            selectAuthorIndex: false,
            selectAuthorLoading: false,
            expertListLoading: false,
        };
    },
    methods: {
        searchFruit() {
            this.pagination.current = 1;
            this.fetchData();
        },
        fetchData() {
            this.loading = true;
            let url = "/talents/fruit/manage/list";
            let that = this;
            let obj = {
                ...this.searchParams,
                pageNo: this.pagination.current,
                pageSize: this.pagination.pageSize
            }
            httpAction(url, obj).then(res => {
                if (res.data.success) {
                    that.dataSource = res.data.result.records;
                    that.total = parseInt(res.data.result.total);
                    this.loading = false;
                }
            }).catch(err => {
                console.log(err)
                this.loading = false;
            })
        },
        handlePaginationChange(page, pageSize) {
            this.pagination.current = page;
            this.pagination.pageSize = pageSize;
            this.fetchData();
        },
        edit(record) {
            this.showModal('edit', record);
        },
        showModal(type, record) {
            this.modal.type = type;
            this.modal.title = type === 'add' ? '新增' : '编辑';
            if(type != 'add'){
                let url = "/talents/fruit/manage/detail";
                let obj = {
                    id: record.id
                }
                httpAction(url, obj).then(res => {
                    if (res.data.success) {
                        this.modal.formData = res.data.result;

                        let fruitType = this.modal.formData.type;
                        let paperType = this.modal.formData.paperType;
                        if(fruitType == 6){
                            paperType == 3 ? this.modal.formData.dcode = '3': this.modal.formData.dcode = '1'
                        }else if(fruitType == 4){
                            this.modal.formData.dcode = '5';
                        }else if(fruitType == 11){
                            this.modal.formData.dcode = '7';
                        }

                        if(this.modal.formData.esTalentFruitAuthorList.length == 0){
                            this.addAuthor();
                        }else{
                            for(let i = 0; i < this.modal.formData.esTalentFruitAuthorList.length; i++){
                                let authorOrgList = this.modal.formData.esTalentFruitAuthorList[i].esTalentFruitAuthorOrgList;
                                if(authorOrgList.length == 0){
                                    this.addOrgName(i);
                                }
                            }
                        }
                    }
                }).catch(err => {
                    console.log(err)
                })
            }else{
                this.modal.formData = {
                  esTalentFruitAuthorList:[]
                };
                this.addAuthor();
            }
            this.modal.visible = true;
        },
        async handleOk() {
            let url = "/talents/fruit/manage/saveOrUpdate";
            let that = this;
            if(this.modal.formData.dcode == '1'){
                this.modal.formData.type = 6;
                this.modal.formData.paperType = 1;
            }else if(this.modal.formData.dcode == '3'){
                this.modal.formData.type = 6;
                this.modal.formData.paperType = 3;
            }else if(this.modal.formData.dcode == '5'){
                this.modal.formData.type = 4;
                this.modal.formData.activityProdType = 1;
                this.modal.formData.paperType = 2;
            }else if(this.modal.formData.dcode == '7'){
                this.modal.formData.type = 11;
            }
            if(!this.modal.formData.name){
              this.$message.error("请填写成果名称！");
              return;
            }
            if(!this.modal.formData.esTalentFruitAuthorList[0].author){
              this.$message.error("请填写作者！");
              return;
            }
            this.modal.formData.esTalentFruitAuthorList = this.setAuthorRankData();
            this.modal.formData.status = 0;
            httpAction(url, this.modal.formData).then(res => {
                if (res.data.success) {
                    that.$message.success('操作成功');
                    this.modal.visible = false;
                    this.searchFruit();
                }
            }).catch(err => {
                console.log(err)
            })
        },
        handleCancel() {
            this.modal.visible = false;
        },
        remove(record) {
            try {
                let url = "/talents/fruit/manage/delete";
                let that = this;
                httpAction(url, record).then(res => {
                    if (res.data.success) {
                        that.$message.success('操作成功');
                        this.searchFruit();
                    }
                }).catch(err => {
                    console.log(err)
                })
            } catch (error) {
                console.error('Error deleting record:', error);
            }
        },
        onChange(date, dateString) {
            this.modal.formData.pubTime = dateString;
        },
        getResultList (query) {
            if (query !== '') {
                this.expertListLoading = true;
                let self = this;
                setTimeout(() => {
                    // self.resultExpertList = self.allExpertList.filter(item => item.author.indexOf(query) > -1);
                    let searchObj = {
                        pageNo: 1,
                        pageSize: 50,
                        talentRealName: query
                    }
                    let url = "/talents/manage/pageList";
                    httpAction(url, searchObj).then(res => {
                        if (res.data.success) {
                            self.resultExpertList = res.data.result.records;
                            self.expertListLoading = false;
                        }
                    }).catch(err => {
                        console.log(err)
                    })
                }, 200);
            } else {
                this.resultExpertList = [];
            }
        },
        changeSelect(value){
            //清空选中
            // this.$refs.select.query = '';
            this.expertListLoading = false;
            this.selectAuthorOrgUserId = value;
        },
        addAuthor(){
            this.modal.formData.esTalentFruitAuthorList.push({
                "author": "",
                "authorId": "",
                "mongoAuthorId": "",
                "ranking": this.modal.formData.esTalentFruitAuthorList.length + 1,
                "fruitId": this.modal.formData.id,
                "esTalentFruitAuthorOrgList": [
                    {
                        "name":"",
                        "ranking":1
                    }
                ]
            })
        },
        addOrgName(authIndex){
            this.modal.formData.esTalentFruitAuthorList[authIndex].esTalentFruitAuthorOrgList.push(
                {
                    "name":"",
                    "ranking": this.modal.formData.esTalentFruitAuthorList[authIndex].esTalentFruitAuthorOrgList.length + 1,
                    "authorId": this.modal.formData.esTalentFruitAuthorList[authIndex].id
                }
            )
        },
        selectAuthor(index){
            this.selectAuthorModal = true;
            this.selectAuthorIndex = index;
            this.selectAuthorOrgUserId = "";
        },
        confirmSetAuthor(){
            if(!this.selectAuthorOrgUserId){
                this.$Message.error("请选择作者！");
                return;
            }
            let selectAuthorObjData = this.resultExpertList.filter(item => item.id == this.selectAuthorOrgUserId);
            this.modal.formData.esTalentFruitAuthorList[this.selectAuthorIndex].authorId = selectAuthorObjData[0].id;
            this.modal.formData.esTalentFruitAuthorList[this.selectAuthorIndex].mongoAuthorId = selectAuthorObjData[0].mongoId;
            this.modal.formData.esTalentFruitAuthorList[this.selectAuthorIndex].author = selectAuthorObjData[0].talentRealName;
            this.modal.formData.esTalentFruitAuthorList[this.selectAuthorIndex].phoneNumber = selectAuthorObjData[0].talentAllPhoneNumber;
            this.modal.formData.esTalentFruitAuthorList[this.selectAuthorIndex].ranking = this.selectAuthorIndex + 1;
            this.selectAuthorModal = false;
            this.resultExpertList = [];
            this.selectAuthorOrgUserId = null;
        },
        cancelSelectAuthor(){
            this.selectAuthorModal = false;
        },
        deleteAuthor(authIndex){
            if(authIndex != 0){
                this.modal.formData.esTalentFruitAuthorList.splice(authIndex, 1);
            }
        },
        deleteOrgName(authIndex, orgIndex){
            if(this.modal.formData.esTalentFruitAuthorList[authIndex].esTalentFruitAuthorOrgList.length > 1) {
                this.modal.formData.esTalentFruitAuthorList[authIndex].esTalentFruitAuthorOrgList.splice(orgIndex, 1);
            }
        },
        // 重新优化作者排名数据
        setAuthorRankData(){
            let newAuthorArr = [];
            let authorArr = this.modal.formData.esTalentFruitAuthorList;
            if(authorArr.length > 0){
                for (var i=0;i<authorArr.length;i++){
                    let authorObj = {};
                    authorObj.fruitId = this.modal.formData.id;
                    authorObj.id = authorArr[i].id;
                    authorObj.author = authorArr[i].author;
                    authorObj.authorId = authorArr[i].authorId;
                    authorObj.mongoAuthorId = authorArr[i].mongoAuthorId;
                    authorObj.ranking = i+1;

                    let newOrgArr = [];
                    let orgArr = authorArr[i].esTalentFruitAuthorOrgList;
                    for (var j=0;j<orgArr.length;j++){
                        let orgObj = {};
                        orgObj.id = orgArr[j].id;
                        orgObj.authorId = orgArr[j].authorId;
                        orgObj.name = orgArr[j].name;
                        orgObj.ranking = j+1;
                        newOrgArr.push(orgObj);
                    }
                    authorObj.esTalentFruitAuthorOrgList = newOrgArr;
                    newAuthorArr.push(authorObj);
                }
            }
            return newAuthorArr;
        }
    }
};
</script>

<style scoped>
/* 样式 */
</style>
